/*
  Copyright © 2010  Vinícius dos Santos Oliveira

      This file is part of Touché.

      Touché is free software: you can redistribute it and/or modify
      it under the terms of the GNU Lesser General Public License as published
      by the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU Lesser General Public License for more details.

      You should have received a copy of the GNU Lesser General Public License
      along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */

#include <QGraphicsSceneMouseEvent>
#include "scribbleareaitem.h"
#include <QPixmap>

ScribbleAreaItem::ScribbleAreaItem(QImage *image, QGraphicsItem *parentItem) :
        ImageItem(image, parentItem),
        paintDevice(image),
        pen(QPen(QBrush(Qt::black, Qt::SolidPattern), 2., Qt::SolidLine, Qt::RoundCap)),
        painter(new QPainter(paintDevice)),
        scribbling(false),
        m_null(true)
{
    painter->setPen(pen);
}

ScribbleAreaItem::~ScribbleAreaItem()
{
    delete painter;
}

bool ScribbleAreaItem::openImage(const QString &fileName)
{
    bool wasSuccessful = paintDevice->load(fileName);
    if(wasSuccessful){
        ImageItem::update();
        painter->begin(paintDevice);
        painter->setPen(pen);
    }
    return wasSuccessful;
}

bool ScribbleAreaItem::saveImage(const QString &fileName, const char * format)
{
    return paintDevice->save(fileName, format);
}

void ScribbleAreaItem::setPen(const QPen &pen)
{
    painter->setPen(pen);
}

void ScribbleAreaItem::setCompositionMode(QPainter::CompositionMode mode)
{
    painter->setCompositionMode(mode);
}

void ScribbleAreaItem::clearImage()
{
    m_null = false;
    painter->setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter->fillRect(QRect(0, 0, 640, 480), Qt::transparent);
    painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
    ImageItem::update();
}

void ScribbleAreaItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        lastPoint = event->pos();
        painter->drawPoint(lastPoint);
        scribbling = true;
        ImageItem::update();
    }
}

void ScribbleAreaItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if((event->buttons() & Qt::LeftButton) && scribbling){
        QPointF cur = event->pos();
        painter->drawLine(lastPoint, cur);
        lastPoint = cur;
    }
    ImageItem::update();
}

void ScribbleAreaItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton && scribbling){
        QPointF cur = event->pos();
        painter->drawLine(lastPoint, cur);
        lastPoint = cur;
        scribbling = false;
        m_null = false;
    }
}
